package cc.xpcas.raft.context;

import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

import cc.xpcas.raft.component.SimpleThreadFactory;

/**
 * @author xp
 */
public class ScheduledExecutor {

    private static final AtomicInteger poolCounter = new AtomicInteger(0);

    private ScheduledExecutorService executor;

    public ScheduledExecutor() {
        executor = Executors.newScheduledThreadPool(2, new SimpleThreadFactory("raft-scheduled-" + poolCounter.incrementAndGet()));
    }

    public Future<?> schedule(Runnable origin, long delayInMillis) {
        ScheduledFuture<Void> future = new ScheduledFuture<>(origin);
        java.util.concurrent.ScheduledFuture outerFuture = executor.schedule(future, delayInMillis, TimeUnit.MILLISECONDS);
        future.setOuterFuture(outerFuture);
        return future;
    }
}
